<template>
  <view class="counter" :class="{ small }">
    <text class="reduce" @click="reduce" v-if="count > 0" :class="{ disabled: !enableReduce }">-</text>
    <input class="countNum" type="number" v-if="count > 0" v-model.number="count" @blur="onBlur" @focus="onFocus" />
    <text class="add" @click="add" :class="{ disabled: !enableAdd }">+</text>
  </view>
</template>

<script>
  export default {

    name: 'commodityNumberInput',

    data () {
      return {
        count: 0,
        oldCount: 1,
      };
    },

    props: {
      value: {
        type: Object,
      },
      max: {
        type: Number,
        default: 99,
      },
	  ids :{
		  type: Number, 
	  },
      small: Boolean,
    },

    computed: {
      enableAdd () {
        return this.count < this.max;
      },
      enableReduce () {
        return this.count > 0;
      },
    },

    watch: {
      value () {
        this.count = this.value.num;
      },

      count () {
        this.$emit('input', this.count);
      },
    },

    mounted () {
      this.count = this.value.num;
    },

    methods: {
      reduce () {
        if (this.enableReduce) {
          this.count = this.count - 1;
          this.emitChange();
        }
      },
      add () {
        if (this.enableAdd) {
          this.count = this.count + 1;
          this.emitChange();
        }
      },
      onFocus () {
        this.oldCount = this.count;
      },
      onBlur () {
        if (this.count >= this.max) {
          this.count = this.max;
        }
        if (this.count <= 1) {
          this.count = 0;
        }
        if (this.oldCount !== this.count) {
          this.emitChange();
        }
      },
      emitChange () {
        this.$emit('change', this.count,this.value);
      },
    },
  };
</script>

<style lang="scss" scoped>
	.counter {
		display: flex;

		.reduce,
		.add {
			width: 28px;
			height: 28px;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 24px;
			line-height: 23px;

			// font-weight: bolder;
			&.disabled {
				opacity: 0.5;
			}
		}

		.reduce {
			background: rgba(239, 65, 41, 0.2);
			color: $uni-text-color-zbt-f;
		}

		.countNum {
			margin: 0 10px;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 48px;
			font-size: 16px;
			color: $uni-text-color;
			background-color: $qy-bg-popu-list-n-color;
		}

		.add {
			background: $uni-text-color-zbt-f;
			color: $uni-text-color;
		}

		&.small {
			.countNum {
				margin: 0 10px;
				width: 48px;
			}
		}

	}
</style>